# time:2019/7/26
# text:第一个接口
import json

from django.http import HttpResponse, JsonResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import permissions, viewsets
from rest_framework.parsers import JSONParser, FormParser

# from apps.models import UserInfo, UserToken
from apps.Serializers import User_Serializer, Token_Serializer
from apps.Serializers import UserSerializer, GroupSerializer

from rest_framework.views import APIView
from  django.contrib.auth.models import User,Group
from apps import models

from django.urls import reverse
def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding="utf-8"))
    return m.hexdigest()


class AuthView(APIView):
    # authentication_classes = [BaseAuthentication,]

    def get(self, request, *args, **kwargs):
        # self.dispatch
        token = request.data.get('token')
        print("------------",request.data)
        print("request.version:", request.version)
        # first()返回总数
        # obj = models.UserToken.objects.filter(token=token).first()
        obj = models.UserToken.objects.filter(token=token)
        ret = {'code': 1000, 'msg': "查询成功"}
        try:
            if token == None or token == "":
                ret['code'] = 1002
                ret['msg'] = "token不能为空"

            elif not obj:
                ret['code'] = 1003
                ret['msg'] = "token错误"
            # 通过 关联字段查询外键数据直接展示数据，不用格式化
            # else:
            #     names = obj.get().user.username
            #     pw = obj.get().user.password
            #     ret['user'] = names
            #     ret['password'] = pw

        except Exception as e:

            ret['code'] = 1004
            ret['msg'] = "请求异常"
        ser = Token_Serializer(instance=obj, many=True, context={"request": request})
        ret["data"] = ser.data
        return HttpResponse(json.dumps(ret, ensure_ascii=False))
        """
        obj=UserInfo.objects.all()
        ser=User_Serializer(instance=obj,many=True)
        rets={'code': 1000, 'msg': "查询成功","data":ser.data}
        print(rets)
        return HttpResponse(json.dumps(rets ,ensure_ascii=False))
        # 查询返回
        {
    "code": 1000,
    "msg": "查询成功",
    "data": [
        {
            "id": 1,
            "user_type": 1,
            "username": "jack1",
            "password": "123456"
        },
        {
            "id": 2,
            "user_type": 2,
            "username": "jack2",
            "password": "123456"
        }
    ]
}
        """

    def post(self, request, *args, **kwargs):
        ret = {'code': 100, 'msg': "登录成功"}
        try:
            # 2 application/json 获取
            # getlist返回的是列表
            # user1 = request.data.getlist('uesrname')
            # usernames = ['zhangning', 'hello'] (list)
            user = request.data.get('uesrname')
            pwd = request.data.get('password')
            obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
            # obj2 = models.UserInfo.objects.filter(username=user, password=pwd)
            if not obj:
                ret['code'] = 1001
                ret['msg'] = "用户名或者密码错位"
            token = md5(user)
            # 存在就更新，不存在就创建
            print("-------------", token)
            models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
            ret['tonken'] = token
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = "请求异常"
        return JsonResponse(ret)





# class UserView(viewsets.ModelViewSet):
#     serializer_class = Token_Serializer
#     queryset = models.UserToken.objects.all()
#     filter_backends = (DjangoFilterBackend,)
#     # 设置过滤字段,这里设置过滤用户的名字和粉丝数
#     # search_fields = ('id')
#

class User_list(viewsets.ModelViewSet):

    def list(self, request, *args, **kwargs):

        token = request.data.get('token')
        # print("------------", request.data)
        # print("request.version:", request.version)
        # first()返回总数
        # obj = models.UserToken.objects.filter(token=token).first()
        obj = models.UserToken.objects.filter(token=token)
        ret = {'code': 1000, 'msg': "查询成功"}
        try:
            if token == None or token == "":
                ret['code'] = 1002
                ret['msg'] = "token不能为空"

            elif not obj:
                ret['code'] = 1003
                ret['msg'] = "token错误"
            # 通过 关联字段查询外键数据直接展示数据，不用格式化
            # else:
            #     names = obj.get().user.username
            #     pw = obj.get().user.password
            #     ret['user'] = names
            #     ret['password'] = pw

        except Exception as e:

            ret['code'] = 1004
            ret['msg'] = "请求异常"
        ser = Token_Serializer(instance=obj, many=True, context={"request": request})
        ret["data"] = ser.data
        return HttpResponse(json.dumps(ret, ensure_ascii=False))
#


class UserViewSet(viewsets.ModelViewSet):
    """
    允许用户查看或编辑的API路径。
    """
    # queryset = User.objects.all().order_by('-date_joined')
    # serializer_class = UserSerializer
    serializer_class = UserSerializer
    queryset = User.objects.all()

class GroupViewSet(viewsets.ModelViewSet):
    """
    允许组查看或编辑的API路径。
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer